#!/bin/bash

. ${SCRIPTS:-/}start-utils
set -euo pipefail
isDebugging && set -x

IFS=$'\n\t'

if [ "${VERSION}" != "LATEST" ] && [ "${VERSION}" != "PURPUR" ] ; then
  log "ERROR: Airplane server type only supports VERSION=LATEST, VERSION=PURPUR."
  exit 1
fi

: ${AIRPLANE_TYPE:=airplane}

if [ "${VERSION}" = "LATEST" ] ; then
  AIRPLANE_TYPE="airplane"
fi

if [ "${VERSION}" = "PURPUR" ]; then
  AIRPLANE_TYPE="airplanepurpur"
fi

log "Using ${AIRPLANE_TYPE} 1.17.1 (1.18 unsupported - use Paper/Pufferfish/Purpur for newer versions)"

export SERVER=${AIRPLANE_TYPE}-1.17.1.jar

log "Removing old Airplane versions ..."
shopt -s nullglob
for f in airplane*.jar; do
  [[ $f != $SERVER ]] && rm $f
done

if [ ! -f "$SERVER" ] || isTrue "${FORCE_REDOWNLOAD:-false}"; then
    downloadUrl="https://airplane.gg/dl/launcher-${AIRPLANE_TYPE}1.17.1.jar"
    log "Downloading Airplane from $downloadUrl ..."
    if ! get -o "$SERVER" "$downloadUrl"; then
      log "ERROR: failed to download from $downloadUrl (status=$?)"
      exit 3
    fi
fi

# Normalize on Spigot for later operations
export FAMILY=SPIGOT

exec "${SCRIPTS:-/}start-spiget" "$@"
